﻿using System;
using System.Configuration;
using System.Diagnostics;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;

namespace TSharp.Core.Threading
{
    /// <summary>
    /// 文件配置
    /// <para>2011/2/25</para>
    /// 	<para>THINKPADT61</para>
    /// 	<para>tangjingbo</para>
    /// </summary>
    public class LoggingConfigurationSource : IConfigurationSource
    {
        #region Public Methods


        /// <summary>
        /// Adds a handler to be called when changes to the section named <paramref name="sectionName"/> are detected.
        /// </summary>
        /// <param name="sectionName">The name of the section to watch for.</param>
        /// <param name="handler">The handler for the change event to add.</param>
        public void AddSectionChangeHandler(string sectionName, ConfigurationChangedEventHandler handler)
        {
        }


        /// <summary>
        /// Retrieves the specified <see cref="T:System.Configuration.ConfigurationSection"/>.
        /// </summary>
        /// <param name="sectionName">The name of the section to be retrieved.</param>
        /// <returns>
        /// The specified <see cref="T:System.Configuration.ConfigurationSection"/>, or <see langword="null"/> (<b>Nothing</b> in Visual Basic)
        /// if a section by that name is not found.
        /// </returns>
        public ConfigurationSection GetSection(string sectionName)
        {
            if (sectionName.Equals("loggingConfiguration", StringComparison.CurrentCulture))
            {
                // Logging configuration                       

                var loggingSettings = new LoggingSettings();

                loggingSettings.DefaultCategory = "General";

                loggingSettings.TracingEnabled = true;

                loggingSettings.LogWarningWhenNoCategoriesMatch = true;


                // Listners                  

                var listenerReference = new TraceListenerReferenceData();

                listenerReference.Name = "RollingFiletLogListener";


                var rollingFlatFileTraceListenerData = new RollingFlatFileTraceListenerData();

                rollingFlatFileTraceListenerData.FileName = "mylog.txt";

                rollingFlatFileTraceListenerData.RollSizeKB = 1024;

                rollingFlatFileTraceListenerData.RollInterval = RollInterval.Day;

                rollingFlatFileTraceListenerData.RollFileExistsBehavior = RollFileExistsBehavior.Increment;

                rollingFlatFileTraceListenerData.Type = typeof (RollingFlatFileTraceListener);

                rollingFlatFileTraceListenerData.ListenerDataType = typeof (RollingFlatFileTraceListenerData);

                rollingFlatFileTraceListenerData.Filter = SourceLevels.All;

                rollingFlatFileTraceListenerData.TraceOutputOptions = TraceOptions.Callstack;

                rollingFlatFileTraceListenerData.Name = "RollingFiletLogListener";
                rollingFlatFileTraceListenerData.RollInterval = RollInterval.Day;
                rollingFlatFileTraceListenerData.Header = "---------------Header---------------";

                rollingFlatFileTraceListenerData.Footer = "-----------------Footer----------------";


                rollingFlatFileTraceListenerData.RollFileExistsBehavior = RollFileExistsBehavior.Overwrite;
                 


                loggingSettings.TraceListeners.Add(rollingFlatFileTraceListenerData);


                // Formatters          

                var template = new StringBuilder();

                template.AppendLine("Timestamp: {timestamp}");

                template.AppendLine("Message: {message}");

                template.AppendLine("Category: {category}");

                template.AppendLine("Priority: {priority}");

                template.AppendLine("EventId: {eventid}");

                template.AppendLine("Severity: {severity}");

                template.AppendLine("Title:{title}");

                template.AppendLine("Machine: {machine}");

                template.AppendLine("Application Domain: {appDomain}");

                template.AppendLine("Process    {processId}");

                template.AppendLine("Process Name: {processName}");

                template.AppendLine("Win32 Thread    {win32ThreadId}");

                template.AppendLine("Thread Name: {threadName}");

                template.AppendLine("Extended Properties: {dictionary({key} - {value})}");

                var formatter = new TextFormatterData();

                formatter.Name = "TextFormatter";

                formatter.Type = typeof (TextFormatter);

                formatter.Template = template.ToString();

                loggingSettings.Formatters.Add(formatter);


                // Category Sources                     

                var exceptionsSource = new TraceSourceData();

                exceptionsSource.TraceListeners.Add(listenerReference);

                exceptionsSource.Name = "Exceptions";

                exceptionsSource.DefaultLevel = SourceLevels.All;

                loggingSettings.TraceSources.Add(exceptionsSource);

                var traceSource = new TraceSourceData();

                traceSource.TraceListeners.Add(listenerReference);

                traceSource.Name = "Trace";

                traceSource.DefaultLevel = SourceLevels.All;

                loggingSettings.TraceSources.Add(traceSource);

                var generalSource = new TraceSourceData();

                generalSource.TraceListeners.Add(listenerReference);

                generalSource.Name = "General";

                generalSource.DefaultLevel = SourceLevels.All;

                loggingSettings.TraceSources.Add(generalSource);


                // Special Sources 

                loggingSettings.SpecialTraceSources.AllEventsTraceSource.Name = "AllEvents";

                loggingSettings.SpecialTraceSources.AllEventsTraceSource.DefaultLevel = SourceLevels.All;

                loggingSettings.SpecialTraceSources.NotProcessedTraceSource.Name = "NotProcessed";

                loggingSettings.SpecialTraceSources.NotProcessedTraceSource.DefaultLevel = SourceLevels.All;

                loggingSettings.SpecialTraceSources.ErrorsTraceSource.Name = "LoggingErrorsAndWarnings";

                loggingSettings.SpecialTraceSources.ErrorsTraceSource.DefaultLevel = SourceLevels.All;

                loggingSettings.SpecialTraceSources.ErrorsTraceSource.TraceListeners.Clear();

                loggingSettings.SpecialTraceSources.ErrorsTraceSource.TraceListeners.Add(listenerReference);


                // Return              

                return loggingSettings;
            }

            return null;
        }

 


        /// <summary>
        /// Removes a handler to be called when changes to section <code>sectionName</code> are detected.
        /// </summary>
        /// <param name="sectionName">The name of the watched section.</param>
        /// <param name="handler">The handler for the change event to remove.</param>
        public void RemoveSectionChangeHandler(string sectionName, ConfigurationChangedEventHandler handler)
        {
        }

        #endregion

        public void Add(string sectionName, ConfigurationSection configurationSection)
        {
            throw new NotImplementedException();
        }

        public void Remove(string sectionName)
        {
            throw new NotImplementedException();
        }

        public event EventHandler<ConfigurationSourceChangedEventArgs> SourceChanged;

        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }
}